<template>
    <div>
      <!--导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>组长分配</el-breadcrumb-item>
      </el-breadcrumb>

      <!--卡片视图区-->
      <el-card >
        <el-row :gutter="20">
          <el-col :span="8">
            <!--因为要切换两个不同的页面，所以以showFlag为判断条件-->
            <el-input placeholder="请输入姓名查找" v-model="page.searchName" clearable @clear="reSetPage()" v-if="showFlag">
              <el-button slot="append" icon="el-icon-search" @click="reSetPage()"></el-button>
            </el-input>
            <el-input placeholder="请输入姓名查找" v-model="page.searchName" clearable @clear="changePage()" v-if="!showFlag">
              <el-button slot="append" icon="el-icon-search" @click="changePage()"></el-button>
            </el-input>
          </el-col>
          <el-col :span="7"><!--getUserListByGroupName-->
            <template>
              <el-select v-model="page.searchGroupName" filterable clearable placeholder="分组筛选" @change="changePage()"
               @clear="getUserList">
                <el-option
                  v-for="item in groupList"
                  :key="item.groupId"
                  :label="item.groupName"
                  :value="item.groupName">
                </el-option>
              </el-select>
            </template>
          </el-col>
        </el-row>
        <!--放表格-->
        <el-table :data="userList" border stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="学号">
            <template slot-scope="scope">
              <span style="color:#67C23A" size="medium"><i class="el-icon-s-opportunity"></i>{{ scope.row.userId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" >
            <template slot-scope="scope">
              <span style="margin-left: 10px;color:#CC9999" v-show="scope.row.userAuthority=='1' && !showFlag"><i class="el-icon-user-solid"></i>{{scope.row.userName}}</span>
              <span style="margin-left: 10px; color:#CC9999" v-show="scope.row.userAuthority=='0' && !showFlag"><i class="el-icon-user" ></i>{{scope.row.userName}}</span>
              <span style="margin-left: 10px; color:#CC9999" v-show="showFlag"><i class="el-icon-user" ></i>{{scope.row.userName}}</span>

            </template>

          </el-table-column>
          <el-table-column label="所属组" prop="group">
            <template slot-scope="scope">
                <span style="color:#F56C6C" v-if="scope.row.group == '还未加入任何分组'">
                  {{scope.row.group}}
                </span>
                <span style="color:#409EFF" v-else>
                  <i class="el-icon-s-home"></i>
                  {{scope.row.group}}
                </span>
            </template>
          </el-table-column>
          <el-table-column label="联系电话">
            <template slot-scope="scope">
              <span style="color:#E6A23C"  size="medium">
                <i class="el-icon-phone"></i>
                {{ scope.row.phone }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="码云账号">
            <template slot-scope="scope">
              <span style="margin-left: 10px ;color:#99CCCC" size="medium">
                <i class="el-icon-s-platform"></i>
                {{ scope.row.codeAccount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="用户状态">
            <template slot-scope="scope">
              <!--后台返回的是true或者false-->
              <span style="color:#67C23A" size="medium" v-if="scope.row.userStatus">
                在职
              </span>
              <span style="color:#F56C6C" size="medium" v-else>
                离职
              </span>
              <!--定义一个开关，用于修改用户的状态-->
              <el-switch v-model="scope.row.userStatus" @change="updateUserStatus(scope.row.userId)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!--当未选择分组是显示以下两个-->
              <el-tooltip effect="dark" content="分配组长" placement="top" :enterable="false" v-show="showFlag">
                <el-button type="warning" icon="el-icon-setting" size="small"
                           @click="showUserAuthorityDialog(scope.row.userId,scope.row.userName)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除成员" placement="top" :enterable="false" v-show="showFlag">
                <el-button type="danger" icon="el-icon-delete" size="small" @click="removeUserById(scope.row.userId)"></el-button>
              </el-tooltip>
              <!--当选择分组时显示以下按钮-->
              <el-button size="mini" type="danger" v-show="!showFlag" v-if="scope.row.userAuthority=='1'"
                         @click="updateUserAuthorityByGNameAndUId(scope.row.userId,scope.row.group)">
                撤销组长
              </el-button>
              <el-button size="mini" type="primary" v-show="!showFlag" v-if="scope.row.userAuthority=='0'"
                         @click="updateUserAuthorityByGNameAndUId(scope.row.userId,scope.row.group)">
                设置组长
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[8,9, 10, 11, 12]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>

      <!--对话框-->
      <el-dialog title="分配组长" :visible.sync="settingDialogVisible" width="25%" @close="settingDialogClear">
        <el-form :model="settingForm" label-width="100px" ref="settingFormRef">
          <el-form-item label="用户名:">
            <el-input v-model="settingForm.userName" size="small"  disabled></el-input>
          </el-form-item>
          <el-form-item label="已加入分组:" label-width="100px">
              <el-select  v-model="settingForm.selectGroupName" filterable clearable>
                <el-option v-for="item in settingForm.userGroupList"
                           :key="item.groupName"
                           :label="item.groupName"
                           :value="item.groupName"
                           :disabled="item.userAuthority==1?true:false">
                </el-option>
              </el-select>
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="settingDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setUserAuthority()" >设置为组长</el-button>
      </span>
      </el-dialog>

    </div>
</template>

<script>
    export default {
      name: "Users",
      data(){
        return {
          page:{
            //当前的页数
            pageNum: 1,
            //每页显示多少条数据
            pageSize: 8,
            searchName: '',
            searchGroupName: '', //组的名称
          },
          userList: [],  //用户列表
          total: 0,
          groupList: [],    //组列表
          settingDialogVisible: false,  //控制对话框的显示与隐藏
          settingForm: {
            userId: '',
            userName: '',
            userGroupList: [],
            selectGroupName: ''
          },
          showFlag: true

        }
      },
      //当页刷新的时候调用
      created() {
        this.getUserList();
        this.getGroupList();
      },
      methods: {
        //重置页码--->对应搜索框
        reSetPage(){
          this.page.pageNum = 1;
          this.page.pageSize = 8;
          this.getUserList();
        },
        async getUserList(){
          //发起get
          const {data: res} = await this.$http.get('user/getUserList',{
            params: {
              pageNum: this.page.pageNum,
              pageSize: this.page.pageSize,
              userName: this.page.searchName,
            }
          });
          if (res.status != 200){
            return this.$message.error(res.msg);
          }
          //获取后端的用户数据
          this.userList = res.data.userList; //用户类表
          this.total = res.data.total;   //总数
          this.showFlag = true;
        },
        async getGroupList(){
          //发起get请求
          const {data: res} = await this.$http.get('teamGroup/getGroups');
          if (res.status != 200){
            return this.$message.error(res.msg);
          }
          //获取后端组数据
          console.log(res);
          this.groupList = res.data;
        },
        handleSizeChange(newPageSize){
          //更新没页的条数
          this.page.pageSize = newPageSize;
          if(!this.showFlag){
            this.getUserListByGroupName();
          }else {
            this.getUserList();
          }

        },
        handleCurrentChange(newPage){
          //更新页码
          this.page.pageNum = newPage;
          if(!this.showFlag){
            this.getUserListByGroupName();
          }else {
            this.getUserList();
          }
        },
        //更新用户状态
        async updateUserStatus(userId){
          //发送put请求
          const {data: res} = await this.$http.put(`user/updateUserStatus/${userId}`);
          if (res.status == 200){
            //刷新列表
            if (this.showFlag){
              this.getUserList();
            }
            if (!this.showFlag) {
              this.getUserListByGroupName();
            }
            return this.$message.success(res.msg);
          }else {
            return this.$message.error(res.msg);
          }
        },
        //通过组名获取用户数据
        async getUserListByGroupName(){
          const {data: res} = await this.$http.get("group/getGroupUserInfoByGroupName",{
            params: {
              groupName: this.page.searchGroupName,
              pageNum: this.page.pageNum,
              pageSize: this.page.pageSize,
              userName: this.page.searchName
            }
          });
          //console.log(res)
          if (res.status != 200){
            return this.$message.error(res.msg);
          }
          this.showFlag = false;
          this.total = res.data.total;
          this.userList = res.data.groupList;
        },
        //显示分配组长的对话框
        async showUserAuthorityDialog(userId,userName){
          this.settingForm.userId = userId;
          this.settingDialogVisible = true;
          this.settingForm.userName = userName;
          //发送get请求获取当前用户加入的组
          const {data: res} = await this.$http.get(`group/getMyGroups/${userId}`);
          console.log(res);
          this.settingForm.userGroupList = res.data;
        },
        //清除分配组长弹窗的数据
        settingDialogClear(){
          //重置表单数据
          this.$refs.settingFormRef.resetFields();
          this.settingForm.userGroupList = [];
          this.settingForm.selectGroupName = '';
        },
        //分配组长按钮触发函数
        async setUserAuthority(){
          if (this.settingForm.selectGroupName === ''){
            return this.$message.error('并未选择分组');
          }else {
            //发送put请求修改用户的角色
            const {data: res} = await this.$http.put(`user/setUserAuthority/${this.settingForm.userId}/${this.settingForm.selectGroupName}`);
            if (res.status != 200){
              return this.$message.error(res.msg);
            }
            console.log(res);
            //关闭窗口
            this.settingDialogVisible = false;
            return this.$message.success(res.msg);
          }
        },
        //点击撤销组长或者分配组长都是触发
        async updateUserAuthorityByGNameAndUId(userId,groupName){
          //put请求
          const {data: res} = await this.$http.put(`group/updateUserAuthorityByGNameAndUId/${userId}/${groupName}`);
          if (res.status != 200){
            return this.$message.error(res.msg);
          }
          console.log(res);
          this.getUserListByGroupName();
          return this.$message.success(res.msg);
        },
        //删除
        async removeUserById(userId){
          const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => {
            return err;
          });
          //当用户确认时，则返回值为字符串：confirm
          //取消时，返回字符串cancel
          if (confirmResult !== 'confirm'){
            return this.$message.info("已取消删除")
          }
          //发送delete请求
          const {data: res} = await this.$http.delete('user/deleteUser/' + userId);
          if (res.status !== 200){
            return this.$message.error(res.msg);
          }
          this.getUserList();
          return this.$message.success(res.msg);

        },
        changePage(){
          this.page.pageNum = 1;
          this.page.pageSize = 8;
          this.getUserListByGroupName();
        }
      }
    }
</script>

<style scoped>


</style>
